<?php
use Core\Helper\ApplicationDirectoryHelper;
use Zend\Json\Json;

$allBlockFile = ApplicationDirectoryHelper::getAllProgramCode();
$fileNameAsJson = Json::encode($allBlockFile);
?>
<div class="ad_title_ctn">
    <h2>Quản lý nhóm block</h2>
</div>
<div class="ad_content_ctn">
    <div id="grid"></div>
    <div id="details"></div>
</div>

<script>

    $(document).ready(function () {

        var allFileNames = <?php echo $fileNameAsJson ?>;


        dataSource = new kendo.data.DataSource({
            type: "jsonp",
            transport: {

                read: function(options) {
                    $.ajax( {
                        url: "<?php echo '/admin/block/block-class-list/'  ?>",
                        data: options.data, // the "data" field contains paging, sorting, filtering and grouping data
                        success: function(result) {
                            if(result.success){
                                options.success(result);
                                $('#error_ctn').html('');
                            }else{
                                $('#error_ctn').html(result.msg);
                                grid = $("#grid").data("kendoGrid");
                                // cancel changes
                                grid.cancelChanges();
                            }
                        },
                        dataType: "json",
                        type: "POST"

                    });
                },


                create: function(options) {
                    $.ajax( {
                        url: "<?php echo '/admin/block/add-block-class' ?>",
                        data: options.data, // the "data" field contains paging, sorting, filtering and grouping data
                        success: function(result) {
                            if(result.success){
                                grid = $("#grid").data("kendoGrid");
                                data = grid.dataItem("tr:eq(0)");
                                data.id = result.id;
                                options.success(options.data.models);
                                $('#error_ctn').addClass('blue_text').html('Thêm thành công.');
                            }else{
                                $('#error_ctn').removeClass('blue_text').html(result.msg);
                                grid = $("#grid").data("kendoGrid");
                                // cancel changes
                                grid.cancelChanges();
                            }
                        },
                        dataType: "json",
                        type: "POST"
                    });
                },
                destroy: function(options) {
                    $.ajax( {
                        url: "/admin/block/remove-block-class",
                        data: options.data,
                        success: function(result) {
                            if(result.success){
                                options.success(result);
                                $('#error_ctn').html('');
                            }else{
                                $('#error_ctn').html(result.msg);
                                grid = $("#grid").data("kendoGrid");
                                // cancel changes
                                grid.cancelChanges();
                            }
                        },
                        dataType: "json",
                        type: "POST"

                    });
                },
                update: function(options) {
                    // make AJAX request to the remote service

                    $.ajax( {
                        url: "/admin/block/update-block-class",
                        data: options.data, // the "data" field contains paging, sorting, filtering and grouping data
                        success: function(result) {
                            if(result.success){
                                options.success(result);
                                $('#error_ctn').html('');
                            }else{
                                $('#error_ctn').html(result.msg);
                                grid = $("#grid").data("kendoGrid");
                                // cancel changes
                                grid.cancelChanges();
                            }
                        },
                        dataType: "json",
                        type: "POST"
                    });
                }
            },
//            ,group: [{ field: "category" }],
            schema: {
                model: {
                    id: "id",
                    fields: {
                        id: {editable: false,  type: "number" },
                        name: { type: "string" ,validation: { required: true }},
                        program_code: { type: "string" ,validation: { required: true}},
                        description: { type: "string" }
                    }
                },
                data:'rows'
            },
//                    batch: true,
            pageSize: 100
        });

        $("#grid").kendoGrid({
            dataSource: dataSource,
            navigatable: true,
            pageable: false,
            columnMenu: true,
            sortable: true,
            resizable:true,
            toolbar: ["create"],


            columns: [
                { field: "name", title: "Tên", width: 100},
                { field: "description", title: "Mô tả", width: 120 },
                { field: "program_code", title: "Tên file", width: 120,  editor: function(container, options) {
                    // create an input element
                    var input = $("<input/>");
                    // set its name to the field to which the column is bound ('name' in this case)
                    input.attr("name", options.field);
                    // append it to the container
                    input.appendTo(container);
                    // initialize a Kendo UI AutoComplete
                    input.kendoComboBox({
                        dataTextField: "text",
                        dataValueField: "value",
                        dataSource: allFileNames
                    });
                }},
                { command:  [{ text: "Sử dụng", click: showDetails },{name: "edit", text: "", className: "grd_edit_btn"},{name: "destroy", text: ""}],  title: "&nbsp;", width: 70 }

            ],
            editable: "popup",
            edit:function(e){
                e.container.data('kendoWindow').bind('activate',function(ex){
                    nameInput = e.container.find('input[name="name"]');
                    nameInput.select();
                    nameInput.focus();
                    e.container.keypress(function(event){
                        //if the key press is ESC
                        if (event.keyCode === 27) {
                            //close the KendoUI window
                            e.container.data("kendoWindow").close();
                        }
                    });
                    if(e.model.isNew())
                        e.container.data('kendoWindow').title('Thêm mới');
                    else
                        e.container.data('kendoWindow').title('Sửa');
                })

            }

        });


        wnd = $("#details")
                .kendoWindow({
                    title: "Các block sử dụng",
                    modal: true,
                    visible: false,
                    resizable: false,
                    width: 300
                }).data("kendoWindow");

        detailsTemplate = kendo.template($("#template").html());

    });


    function showDetails(e) {
        e.preventDefault();
        dataItem = this.dataItem($(e.currentTarget).closest("tr"));
        $.post('/admin/block/get-block-usage',{id:dataItem.id},function(result){
            if (result.success){
                wnd.content(detailsTemplate(result.data));
                wnd.center().open();
            }

        },'json');
    }

</script>
<script type="text/x-kendo-template" id="template">
    <div id="details-container">
        <h3>#= name #</h3>
        <em>Số lượng các block sử dụng: </em><h3>#= usage #</h3>
    </div>
</script>